package drone;

import com.jme3.asset.AssetManager;
import com.jme3.material.Material;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;

/**
 *
 * @author Robert Verginien Nickel
 */
public class Barrier {
    private BarrierStatus status;
    final float TIMEGATEISOPENED = 5.0f;
    final float OPENINGTIME = 1.0f;
    private float openedPercent;
    private float timeLeft;
    AssetManager assetManager;
    Spatial foot;
    Spatial arm;
    
    public Barrier(AssetManager assetManager, Node node){
        status = BarrierStatus.CLOSED;
        this.assetManager = assetManager;
        timeLeft = TIMEGATEISOPENED;
        paintGate(node);
    }
    
    public void update(float tpf) {
        switch(status){
            case OPENING :
                if(openedPercent >= 1f){
                    status = BarrierStatus.OPENED;
                }
                else{
                    openBarrier(tpf);
                }
                break;
            case CLOSING :
                if(openedPercent < 0.02f){
                    status = BarrierStatus.CLOSED;
                }
                else{
                    closeBarrier(tpf);
                }
                break;
            case OPENED :
                if(timeLeft >= 0){
                    timeLeft = timeLeft - tpf;
                }
                else{
                    timeLeft = TIMEGATEISOPENED;
                    status = BarrierStatus.CLOSING;
                }
            break;
        }
    }
    
    private void paintGate(Node node){        
        foot = assetManager.loadModel("Models/barrierFoot.obj");
        Material mat_foot = new Material( 
            assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
        foot.setMaterial(mat_foot);
        foot.setLocalTranslation(8.5f, 0f, 3.0f);

        arm = assetManager.loadModel("Models/barrierArm.obj");
        Material mat_arm = new Material( 
            assetManager, "Common/MatDefs/Misc/ShowNormals.j3md");
        arm.setMaterial(mat_arm);
        arm.setLocalTranslation(8.5f, 0f, 3.0f);

        node.attachChild(foot);
        
        Node pivot = new Node();
        pivot.attachChild(arm);
        pivot.setLocalTranslation(0, 0.7f, 0);
        node.attachChild(pivot);
    }
    
    public void openBarrier(float tpf){
        //For a Rotation about 90° (which are pi/2)
        float rotationZ = (float) (Math.PI/2) / OPENINGTIME * tpf;
        arm.rotate(0f,0f,rotationZ);
        openedPercent = openedPercent + tpf / OPENINGTIME;
    }
    
    public void closeBarrier(float tpf){
        //For a Rotation about 90° (which are pi/2)
        float rotationZ = (float) (Math.PI/2) / OPENINGTIME * tpf;
        arm.rotate(0f,0f,-rotationZ);
        openedPercent = openedPercent - tpf / OPENINGTIME;
    }
    
    public void setStatus(BarrierStatus status){
        this.status = status;
    }
}
